import { ref, onMounted, onUnmounted } from 'vue';

const defaultParams = {
  small: 'calc(100vh - 335px)',
  middle: 'calc(100vh - 315px)',
  large: 'calc(100vh - 345px)',
};
// 按照惯例，组合式函数名以“use”开头
export function useTableHeight(params) {
  const { small, middle, large } = params;
  // 因为在窄屏下title有折行，这里动态计算表格滚动高度让表格高度自适应
  const getCurrentHeight = () => {
    const width = window.innerWidth;
    let currentHeight = '';
    if (width < 1440) {
      currentHeight = small || defaultParams.small;
    } else if (width < 1750) {
      currentHeight = middle || defaultParams.middle;
    } else {
      currentHeight = large || defaultParams.large;
    }
    return currentHeight;
  };
  // 初始化
  const tableScrollY = ref(getCurrentHeight());

  // 窗体大小变化更改其状态。
  const getTableScrollHeight = useDebounceFn(() => {
    const height = getCurrentHeight();
    tableScrollY.value = height;
  }, 500);

  // 一个组合式函数也可以挂靠在所属组件的生命周期上
  // 来启动和卸载副作用
  onMounted(() => window.addEventListener('resize', getTableScrollHeight));
  onUnmounted(() => window.removeEventListener('resize', getTableScrollHeight));

  // 通过返回值暴露所管理的状态
  return tableScrollY;
}
